package com.xz.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 14-8-9
 * Time: 下午7:55
 * To change this template use File | Settings | File Templates.
 */
public class Client {
    private CloseableHttpClient httpClient;
    private HttpHost httpHost;
    private HttpRequestBase httpMethod;
    private String charset;

    public Client(String host) {
        if (httpClient == null) {
            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
            connectionManager.setMaxTotal(25);
            connectionManager.setDefaultMaxPerRoute(25);
            connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost(host)), 50);
            httpClient = HttpClients.custom()
                    .setConnectionManager(connectionManager)
                    .build();
            System.out.println("httpClient create");
        }
    }

    public String getContent() {
        String content = null;
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpMethod);
            HttpEntity httpEntity = response.getEntity();
            content = EntityUtils.toString(httpEntity, charset);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(response!=null)
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
        }
        return content;
    }

    public HttpHost getHttpHost() {
        return httpHost;
    }

    public void setHttpHost(HttpHost httpHost) {
        this.httpHost = httpHost;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public HttpRequestBase getHttpMethod() {
        return httpMethod;
    }

    public void setHttpMethod(HttpRequestBase httpMethod) {
        this.httpMethod = httpMethod;
    }
}
